<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userinfo=$this->auth->getUserinfo();

        $firedcount=\app\common\model\User::where('pid',$userinfo['id'])->count();

        $userProfitarr=\app\admin\model\MachineProfitLog::where('user_id',$userinfo['id'])->select();
        $allprofit=0;
        foreach ($userProfitarr as $key => $value) {
            $allprofit=$allprofit+$value['profit'];
        }

        unset($userinfo['token']);

        $userinfo['distribution_name']='用户';
        $user_distribution_find=\app\admin\model\DistributionInfo::where('id', $userinfo['distribution_id'])->find();
        if($user_distribution_find){
            $userinfo['distribution_name']=$user_distribution_find['distribution_name'];
        }else if($userinfo['distribution_id']==0){
            $userinfo['distribution_name']='会员';
        }
        $userinfo['machine']=\app\admin\model\Machine::where('user_id',$userinfo['id'])->count();
        $userinfo['firedcount']=$firedcount;
        $userinfo['allprofit']=$allprofit;
        $this->success('用户信息获取成功', ['welcome' =>  $userinfo]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     * @param string $pid     邀请人id
     */
    public function register()
    {
//        $username = $this->request->post('username');
        $password = $this->request->post('password');
//        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $pid = $this->request->post('pid');
//        if (!$username || !$password) {
//            $this->error(__('Invalid parameters'));
//        }

        if (!$mobile || !$password|| !$code|| !$pid) {
            $this->error(__('Invalid parameters'));
        }
        $parent_find=\app\admin\model\User::where('id',$pid)->find();
        if(!$parent_find){
            $this->error(__('邀请人账号异常，无效注册'));
        }
//        if($parent_find['distribution_id']==-1){
//            $this->error(__('无自购用户无法邀请注册'));
//        }

//        if ($email && !Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }

        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        //短信验证码验证
        $ret = Sms::check($mobile, $code, 'register');

        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($mobile ,$password, $mobile, [], $pid);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     * @param string $walletaddresss     钱包地址
     */
    public function profile()
    {
        $user = $this->auth->getUser();

//        $username = $this->request->post('username');
        $username = null;
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
//        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $avatar = $this->request->post('avatar');
        $walletaddresss = $this->request->post('walletaddresss');

        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($bio) {
            $user->bio = $bio;
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($walletaddresss) {
            $user->walletaddresss = $walletaddresss;
        }
        $re=$user->save();
        $this->success(__('修改成功'), $re);
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
//        $type = $this->request->post("type");
        $type = 'mobile';
        $mobile = $this->request->post("mobile");
//        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            //暂时注释手机短信验证
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        }
//        else {
//            if (!Validate::is($email, "email")) {
//                $this->error(__('Email is incorrect'));
//            }
//            $user = \app\common\model\User::getByEmail($email);
//            if (!$user) {
//                $this->error(__('User not found'));
//            }
//            $ret = Ems::check($email, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Ems::flush($email, 'resetpwd');
//        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 修改密码
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 新密码
     */
    public function changepwd()
    {

        $oldpassword = $this->request->post("oldpassword");
        $newpassword = $this->request->post("newpassword");

        //模拟一次登录
        $this->auth->direct($this->auth->getUserinfo()['id']);
        $ret = $this->auth->changepwd($newpassword, $oldpassword);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }

    }
    /**
     * 修改支付密码
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $oldpassword 新密码
     */
    public function changepaypwd()
    {
        $oldpaypwd = $this->request->post("oldpaypwd");
        $newpaypwd = $this->request->post("newpaypwd");


        if (!$newpaypwd || !$oldpaypwd && !$newpaypwd==$oldpaypwd) {
            $this->error(__('缺少新旧密码或新旧密码相同'));
        }

        $user = \app\common\model\User::where('id',$this->auth->getUserinfo()['id'])->find();

        $md5_input_old_paypwd = $this->auth->getEncryptPassword($oldpaypwd, $user['paypasswordsalt']);

        $ret=false;
        if ($md5_input_old_paypwd == $user['paypassword']) {
            $paypasswordsalt = Random::alnum();
            $md5_input_new_paypwd = $this->auth->getEncryptPassword($newpaypwd, $paypasswordsalt);
            $ret = \app\common\model\User::where('id',$this->auth->getUserinfo()['id'])->update(['paypassword'=>$md5_input_new_paypwd,'paypasswordsalt'=>$paypasswordsalt]);

        }
        if ($ret) {
            $this->success(__('更改支付密码成功'));
        } else {
            $this->error(__('更改支付密码失败'));
        }
    }


    /**
     * 重置支付密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpaypwd 新支付密码
     * @param string $captcha     验证码
     */
    public function resetpaypwd()
    {
//        $type = $this->request->post("type");
        $type = 'mobile';
        $mobile = $this->request->post("mobile");

        $newpaypwd = $this->request->post("newpaypwd");
        $captcha = $this->request->post("captcha");

        if (!$newpaypwd || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            //暂时注释手机短信验证
//            $ret = Sms::check($mobile, $captcha, 'resetpwd');
//            if (!$ret) {
//                $this->error(__('Captcha is incorrect'));
//            }
//            Sms::flush($mobile, 'resetpwd');
            $paypasswordsalt = Random::alnum();
            $md5_input_new_paypwd = $this->auth->getEncryptPassword($newpaypwd, $paypasswordsalt);
            $ret = \app\common\model\User::where('id',$this->auth->getUserinfo()['id'])->update(['paypassword'=>$md5_input_new_paypwd,'paypasswordsalt'=>$paypasswordsalt]);
            if ($ret) {
                $this->success(__('重置支付密码成功',$ret));
            } else {
                $this->error($this->auth->getError());
            }
        }


    }


    /**
     * 钱包四种币值(B C)
     * @ApiMethod (POST)
     */
    public function wallet()
    {
        $user_id=$this->auth->getUser()['id'];
        $walletRe=\app\admin\model\user\Wallet::where('user_id',$user_id)->select();

        $this->success(__('获取成功'), $walletRe);
    }

    /**
     * 钱包记录(B C)
     * @ApiMethod (POST)
     */
    public function walletlog()
    {
        $user_id = $this->auth->getUserinfo()['id'];
        $where['user_id']=['=',$user_id];

        $coin_type = $this->request->post("coin_type");
        if($coin_type){
            $where['coin_type']=['=',$coin_type];
        }
        $state = $this->request->post("state");
        if($state){
            $where['state']=['=',$state];
        }
        $stime = $this->request->post("stime");
        $etime = $this->request->post("etime");

        if($stime && $etime){
            $where['createtime']=['between',[$stime,$etime]];

        }

        $walletRe=\app\admin\model\user\WalletLog::where($where)->paginate(10);

        $this->success(__('获取成功'), $walletRe);
    }

    /**
     * 用户设备信息数量（B C）
     * @ApiMethod (POST)
     */
    public function machineCount()
    {
        $where['user_id']=['=',$this->auth->getUserinfo()['id']];

        $topgoodsclass=\app\admin\model\GoodsClass::where('pid','0')->field('id,name')->select();
        for ($i=0; $i <count($topgoodsclass); $i++) {
            $topgoodsclass[$i]['count']=\app\admin\model\Machine::where(['top_goods_class_id'=>$topgoodsclass[$i]['id'],'user_id'=>$this->auth->getUserinfo()['id']])->count();
        }
        $this->success(__('用户设备信息数量获取成功'), $topgoodsclass);

    }

    /**
     * 用户设备信息列表（B C）
     * @ApiMethod (POST)
     */
    public function machinelist()
    {
        $where['user_id']=['=',$this->auth->getUserinfo()['id']];
        $where['top_goods_class_id']=$this->request->post("top_goods_class_id");

        $machinelist=\app\admin\model\Machine::with('todayProfit')->order('id desc')->with('goodsInfo')->where($where)->paginate(10);

        $this->success(__('用户设备信息列表获取成功'), $machinelist);

    }

    /**
     * 用户设备最近收益（B C）
     * @ApiMethod (POST)
     */
    public function machineProfit()
    {
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));

        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'));

        $map['createtime'] = array('between', array($beginToday-6*24*60*60,$endToday-1));
        $map['user_id'] = array('=', $this->auth->getUserinfo()['id']);

        $machineProfit=\app\admin\model\MachineProfitLog::where($map)->select();

        $profitArr=[];
        for ($i=0; $i < 7 ; $i++) {
            $profitArr[$i]=0;
            foreach ($machineProfit as $key => $value) {
                if($value['createtime']>$beginToday-$i*24*60*60 && $value['createtime']<$endToday-$i*24*60*60-1){
                    $profitArr[$i]=$profitArr[$i]+$value['profit'];
                }
            }
        }
        $this->success(__('用户设备最近收益获取成功'),$profitArr);
    }
    /**
     * 用户提币申请（B C）
     * @ApiMethod (POST)
     */
    public function withdrawcoin()
    {
        $cointype = $this->request->post("cointype");
        $amount = $this->request->post("amount");
        $userinfo=$this->auth->getUser();
        $last_withdrawcoin_find=\app\admin\model\user\UserWithdrawcoin::where('coin_type',$cointype)->where('user_id',$userinfo['id'])->where('status',0)->find();
        if($last_withdrawcoin_find){
            $this->error('上一次的'.$cointype.'提现尚未完成');
        }

        if($cointype=='USDT' && $userinfo['money']>=$amount && $amount>0){
            $coin_data=[
                'user_id'=>$userinfo['id'],
                'coin_type'=>$cointype,
                'amount'=>$amount,
                'createtime'=>time()
            ];
            \app\admin\model\user\UserWithdrawcoin::insert($coin_data);
            $this->success($cointype.'提现申请已提交',$amount);
        }

        if($cointype=='HNT' && $userinfo['HNT']>=$amount && $amount>0){
            $coin_data=[
                'user_id'=>$userinfo['id'],
                'coin_type'=>$cointype,
                'amount'=>$amount,
                'createtime'=>time()
            ];
            \app\admin\model\user\UserWithdrawcoin::insert($coin_data);
            $this->success($cointype.'提现申请已提交',$amount);
        }

        $this->error('提现申请参数有误');
    }

    /**
     * 用户社区/好友（B C）
     * @ApiMethod (POST)
     */
    public function community()
    {
        $userinfo=$this->auth->getUser();

        $user_community_sel=\app\admin\model\User::where('pid',$userinfo['id'])->field('pid,nickname,c_buy_number,createtime,prevtime,logintime,jointime')->paginate(10);

        $allusdt=Db::name('user_money_log')->where('user_id',$userinfo['id'])->where('memo','in','分销身份分U,邀请消费分U')->select();
        $re['USDT']=0;
        foreach ($allusdt as $key => $value) {
            $re['USDT']=$re['USDT']+$value['money'];
        }

        $allhnt=Db::name('user_hnt_log')->where('user_id',$userinfo['id'])->select();
        $re['HNT']=0;
        foreach ($allhnt as $key => $value) {
            $re['HNT']=$re['HNT']+$value['HNT'];
        }
        $re['user_community_sel']=$user_community_sel;
        $this->success('用户社群查询',$re);
    }
    /**
     * 用户USDT和HNT记录（B C）
     * @param string $starttime      开始时间
     * @param string $endtime       结束时间
     * @param string $coin_type     币种类型
     * @ApiMethod (POST)
     */
    public function userAccountLog()
    {
        $userinfo=$this->auth->getUser();
        $starttime = $this->request->post("starttime");
        $endtime = $this->request->post("endtime");
        $coin_type = $this->request->post("coin_type");


        $map['user_id']  = ['=',$userinfo['id']];

        if($starttime){
            $map['createtime']  = ['>=',$starttime];
        }
        if($endtime){
            $map['createtime']  = ['<=',$endtime];
        }
        if($coin_type=='USDT'){
            $allusdt=Db::name('user_money_log')->where($map)->order('id desc')->paginate(10);
            $this->success('用户USDT记录',$allusdt);
        }else if($coin_type=='HNT'){
            $allHNT=Db::name('user_hnt_log')->where($map)->order('id desc')->paginate(10);
            $this->success('用户HNT记录',$allHNT);
        }

        $this->error('缺少参数');



    }
}
